import React, { useEffect, useRef, useState } from 'react';
import { Tabs } from 'antd';
import { useSelector, useDispatch ,history } from "umi"
type TargetKey = React.MouseEvent | React.KeyboardEvent | string;



type Props = {
  children: any
}

interface itemType {
  label: any, 
  key: any
}

const MenuTabs = (props: Props) => {

  const [initialItems, setInitialItems] = useState<Array<itemType>>([{label:"主页",key:"/home/index"}]);
  const [activeKey, setActiveKey] = useState(initialItems[0].key);
  const [items, setItems] = useState(initialItems);
  const newTabIndex = useRef(0);

  const menuState = useSelector((state: { menuData:[], menuInData:{title:any,key:any} }) => {
    //state整个仓库i数据，product是仓库命名空间
    return state.menuData
  })

  useEffect(() => {
    if(menuState.menuInData.length!=0){
        const filterTab=items.filter((item)=>{
          return item.key==menuState.menuInData.key
        })
        if(filterTab.length==0){
          const newActiveKey = `${menuState.menuInData.key}`;
          const newPanes = [...items];
          newPanes.push({ label: `${menuState.menuInData.title}`, key: newActiveKey });
          setItems(newPanes);
          setActiveKey(newActiveKey);
        }
      }
      
      

  }, [menuState])


  // const initialItems = [
  //   { label: 'Tab 1', key: '1' },
  //   { label: 'Tab 2', key: '2' },
  //   {
  //     label: 'Tab 3',
  //     key: '3',
  //     closable: false,
  //   },
  // ];



  const onChange = (newActiveKey: string) => {
    setActiveKey(newActiveKey);
    history.push(newActiveKey)

  };

  const add = () => {
    // const newActiveKey = `newTab${newTabIndex.current++}`;
    // const newPanes = [...items];
    // newPanes.push({ label: 'New Tab', key: newActiveKey });
    // setItems(newPanes);
    // setActiveKey(newActiveKey);
  };

  const remove = (targetKey: TargetKey) => {
    let newActiveKey = activeKey;
    let lastIndex = -1;
    items.forEach((item, i) => {
      if (item.key === targetKey) {
        lastIndex = i - 1;
      }
    });
    const newPanes = items.filter((item) => item.key !== targetKey);
    if (newPanes.length && newActiveKey === targetKey) {
      if (lastIndex >= 0) {
        newActiveKey = newPanes[lastIndex].key;
      } else {
        newActiveKey = newPanes[0].key;
      }
    }
    setItems(newPanes);
    setActiveKey(newActiveKey);
  };

  const onEdit = (
    targetKey: React.MouseEvent | React.KeyboardEvent | string,
    action: 'add' | 'remove',
  ) => {
    if (action === 'add') {
      add();
    } else {
      remove(targetKey);
    }
  };

  return (
    <>
      <Tabs
        type="editable-card"
        onChange={onChange}
        activeKey={activeKey}
        onEdit={onEdit}
        items={items}
      />

    </>
  )
}

export default MenuTabs